#include "audio.hpp"

#include "SDL.h"
#include "SDL_mixer.h"

Audio::Audio()
{
	freq = 44100;
	loop = 0;
	playpos = Vec2f (0, 0);
	listen = Vec2f (0, 0);
}

Audio::~Audio()
{
}

#include <iostream>

bool Audio::Open()
{
	bool success = Mix_OpenAudio(freq,
					MIX_DEFAULT_FORMAT,
					MIX_DEFAULT_CHANNELS,
					2048) == 0;
	
	if (success)
	{
		//success = MIX_INIT_OGG & Mix_Init(MIX_INIT_OGG);
	}

	if (!success)
	{
		std::cerr << Mix_GetError() << std::endl;
	}

	Mix_AllocateChannels(32);
	return success;
}

void Audio::Close()
{
	Mix_CloseAudio();
}

void Audio::Loop(int loops)
{
	loop = loops;
}

void Audio::Pos(float x, float y)
{
	playpos.x = x - listen.x;
	playpos.y = y - listen.y;
}

void Audio::Listen(float x, float y)
{
	listen.x = x;
	listen.y = y;
}

int Audio::Vol(int vol, int chan)
{
	return Mix_Volume(chan, vol);
}

#include "sound.hpp"
#include <cmath>

int Audio::SoundPlay(Sound & sound, int chan)
{
	chan = sound.Play(chan, loop);

	Sint16 ang = 0;
	Uint8 dist = 0;

	if (chan > -1)
	{
		ang = 2 * playpos.x + 360;
		dist = std::sqrt(playpos.LenSq());
	}

	Mix_SetPosition(chan, ang, dist);
	return chan;	
}

void Audio::Pause(int chan)
{
	Mix_Pause(chan);
}

void Audio::Resume(int chan)
{
	Mix_Resume(chan);
}

void Audio::Stop(int chan)
{
	Mix_HaltChannel(chan);
}

Audio Aud;
